/**
 * 仕兰微电子 SC7A20 G-Sensor SPI 接口驱动
 * Copyright (c) 2021 深圳市智辰科技有限公司
 * All rights reserved.
 */

#ifndef _DRIVER_SC7A20_H_
#define _DRIVER_SC7A20_H_

#include "nonos.h"
#include "sc7a20_defs.h"


// 驱动数据结构
typedef struct st_driver_sc7a20_t {
	// GPIO 驱动函数
	FUNC_GPIO_Out csn;
	FUNC_GPIO_Out sclk;
	FUNC_GPIO_Out mosi;
	FUNC_GPIO_ReadIn miso;

	uint32_t acc2TrigLevel;
	void (*acc2TrigHandler)(struct st_driver_sc7a20_t *dev, uint32_t acc2, void *cookie);
	void *acc2TrigHandlerCookie;
} driver_sc7a20_t;

/// 写单个寄存器
void sc7a20_write_reg(driver_sc7a20_t *dev, uint8_t addr, uint8_t ch);
/// 读单个寄存器
uint8_t sc7a20_read_reg(driver_sc7a20_t *dev, uint8_t addr);
/// 连续写多个寄存器
void sc7a20_write_regs(driver_sc7a20_t *dev, uint8_t addr, const uint8_t* buf, uint16_t len);
/// 连续读多个寄存器
void sc7a20_read_regs(driver_sc7a20_t *dev, uint8_t addr, uint8_t* buf, uint16_t len);

/// 初始化
void sc7a20_init(driver_sc7a20_t *dev, const sc7a20_reg_t *regs);
/// SC7A20 是否存在
bool sc7a20_exists(driver_sc7a20_t *dev);
/// 低功耗模式
static inline void sc7a20_sleep(driver_sc7a20_t *dev) { sc7a20_write_reg(dev, GS_REG_CTRL1, 0x08); }
/// 关机
static inline void sc7a20_shutdown(driver_sc7a20_t *dev) { sc7a20_write_reg(dev, GS_REG_CTRL1, 0x00); }

/// 读 x/y/z 方向上的加速度(0.01G)
void sc7a20_read_acc_xyz(driver_sc7a20_t *dev, s16 xyz[3]);
/// 读 x/y/z 方向上的矢量加速度的绝对值的平方(x^2 + y^2 + z^2)
uint32_t sc7a20_read_acc2(driver_sc7a20_t *dev);

/// ACC2 触发回调函数
typedef void (*sc7a20_acc2_trig_handler_t)(driver_sc7a20_t *dev, uint32_t acc2, void *cookie);

/// 设置 ACC 触发
/// @param acc 当加速度达到多少个 G，就触发
/// @param handler 触发回调函数
void sc7a20_set_acc_trigger(driver_sc7a20_t *dev, uint32_t acc, sc7a20_acc2_trig_handler_t handler, void *cookie);

/// 中断处理
void sc7a20_int1Handler(driver_sc7a20_t *dev);
void sc7a20_int2Handler(driver_sc7a20_t *dev);

/// 测试
void sc7a20_test(driver_sc7a20_t *dev);


#endif // _DRIVER_SC7A20_H_
